package com.gomro.galaxy.foundation.bi.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gomro.galaxy.core.commons.elastic.ElasticSearchRest;
import com.gomro.galaxy.core.commons.model.Result;
import com.gomro.galaxy.foundation.bi.domain.Constants;
import com.gomro.galaxy.foundation.bi.domain.model.analysis.CustomerTradeVolume;
import com.gomro.galaxy.foundation.bi.engine.util.BoolQueryBuilders;
import com.gomro.galaxy.foundation.bi.query.CustomerTradeQuery;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.Cardinality;
import org.elasticsearch.search.aggregations.metrics.Sum;
import org.elasticsearch.search.aggregations.metrics.TopHits;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 客户交易信息service
 *
 * @author ZhangLei
 */
@Service
public class CustomerTradeService {
    private final ElasticSearchRest rest;
    private final RestHighLevelClient client;
    private final ObjectMapper mapper;
    private static final String INDEX = Constants.BiDataMartIndexPrefix + CustomerTradeVolume.TableName;

    public CustomerTradeService(RestHighLevelClient client, ObjectMapper mapper) {
        this.client = client;
        this.mapper = mapper;
        this.rest = new ElasticSearchRest(client, mapper);
    }

    public Result<List<CustomerTradeVolume>> page(CustomerTradeQuery query) {
        //构建查询
        QueryBuilder queryBuilder = this.getQueryBuilder(query);
        TermsAggregationBuilder orgTerm = AggregationBuilders.terms("terms").field("organizationId").order(BucketOrder.key(true)).size(query.getPage() * query.getLimit());
        AggregationBuilder organizationId = AggregationBuilders.topHits("organizationId").docValueField("organizationId").size(1);
        AggregationBuilder customerName = AggregationBuilders.topHits("customerName").docValueField("customerName.keyword").sort("time", SortOrder.DESC).size(1);
        AggregationBuilder projectManagerName = AggregationBuilders.topHits("projectManagerName").docValueField("projectManagerName.keyword").size(1);
        AggregationBuilder residentName = AggregationBuilders.topHits("residentName").docValueField("residentName.keyword").size(1);
        AggregationBuilder customerServiceName = AggregationBuilders.topHits("customerServiceName").docValueField("customerServiceName.keyword").size(1);
        //询价商品数
        AggregationBuilder inquiryGoodsNumber = AggregationBuilders.sum("inquiryGoodsNumber").field("inquiryGoodsNumber");
        //报价商品数量-原有供应商
        AggregationBuilder originalQuotationNumber = AggregationBuilders.sum("originalQuotationNumber").field("originalQuotationNumber");
        //报价商品数量-平台供应商
        AggregationBuilder platformQuotationNumber = AggregationBuilders.sum("platformQuotationNumber").field("platformQuotationNumber");
        //报价商品数量-未报价
        AggregationBuilder notQuotedGoodsNumber = AggregationBuilders.sum("notQuotedGoodsNumber").field("notQuotedGoodsNumber");
        //定标商品数量-原有供应商
        AggregationBuilder originalTargetGoodsNumber = AggregationBuilders.sum("originalTargetGoodsNumber").field("originalTargetGoodsNumber");
        //定标商品数量-平台供应商
        AggregationBuilder platfromTargetGoodsNumber = AggregationBuilders.sum("platfromTargetGoodsNumber").field("platfromTargetGoodsNumber");
        //订单商品数-原有供应商
        AggregationBuilder originalOrderGoodsNumber = AggregationBuilders.sum("originalOrderGoodsNumber").field("originalOrderGoodsNumber");
        //订单商品数-平台供应商
        AggregationBuilder platfromOrderGoodsNumber = AggregationBuilders.sum("platfromOrderGoodsNumber").field("platfromOrderGoodsNumber");
        //订单数量
        AggregationBuilder orderNumber = AggregationBuilders.sum("orderNumber").field("orderNumber");
        //订单金额-原有供应商
        AggregationBuilder originalOrderAmount = AggregationBuilders.sum("originalOrderAmount").field("originalOrderAmount");
        //订单金额-平台供应商
        AggregationBuilder platfromOrderAmount = AggregationBuilders.sum("platfromOrderAmount").field("platfromOrderAmount");
        //退货金额-原有供应商
        AggregationBuilder originalReturnAmount = AggregationBuilders.sum("originalReturnAmount").field("originalReturnAmount");
        //退货金额-平台供应商
        AggregationBuilder platfromReturnAmount = AggregationBuilders.sum("platfromReturnAmount").field("platfromReturnAmount");
        orgTerm.subAggregation(organizationId);
        orgTerm.subAggregation(customerName);
        orgTerm.subAggregation(projectManagerName);
        orgTerm.subAggregation(customerServiceName);
        orgTerm.subAggregation(residentName);
        orgTerm.subAggregation(inquiryGoodsNumber);
        orgTerm.subAggregation(originalQuotationNumber);
        orgTerm.subAggregation(platformQuotationNumber);
        orgTerm.subAggregation(notQuotedGoodsNumber);
        orgTerm.subAggregation(originalTargetGoodsNumber);
        orgTerm.subAggregation(platfromTargetGoodsNumber);
        orgTerm.subAggregation(originalOrderGoodsNumber);
        orgTerm.subAggregation(platfromOrderGoodsNumber);
        orgTerm.subAggregation(orderNumber);
        orgTerm.subAggregation(originalOrderAmount);
        orgTerm.subAggregation(platfromOrderAmount);
        orgTerm.subAggregation(originalReturnAmount);
        orgTerm.subAggregation(platfromReturnAmount);
        AggregationBuilder count = AggregationBuilders.cardinality("count").field("organizationId").precisionThreshold(30000L);
        SearchResponse search = rest.search(INDEX, ElasticSearchRest.Page.of(1, 0), queryBuilder, null, Arrays.asList(orgTerm, count), null);
        Terms org = search.getAggregations().get("terms");
        List<CustomerTradeVolume> result = org.getBuckets().stream().skip(query.getStartRow()).map(bucket -> {
            int inquiryGoodsNumberSum = ((int) (((Sum) bucket.getAggregations().get("inquiryGoodsNumber")).getValue()));
            int originalQuotationNumberSum = ((int) (((Sum) bucket.getAggregations().get("originalQuotationNumber")).getValue()));
            int platformQuotationNumberSum = ((int) (((Sum) bucket.getAggregations().get("platformQuotationNumber")).getValue()));
            int notQuotedGoodsNumberSum = ((int) (((Sum) bucket.getAggregations().get("notQuotedGoodsNumber")).getValue()));
            int originalTargetGoodsNumberSum = ((int) (((Sum) bucket.getAggregations().get("originalTargetGoodsNumber")).getValue()));
            int platfromTargetGoodsNumberSum = ((int) (((Sum) bucket.getAggregations().get("platfromTargetGoodsNumber")).getValue()));
            int originalOrderGoodsNumberSum = ((int) (((Sum) bucket.getAggregations().get("originalOrderGoodsNumber")).getValue()));
            int platfromOrderGoodsNumberSum = ((int) (((Sum) bucket.getAggregations().get("platfromOrderGoodsNumber")).getValue()));
            int orderNumberSum = ((int) (((Sum) bucket.getAggregations().get("orderNumber")).getValue()));
            double originalOrderAmountSum = ((Sum) bucket.getAggregations().get("originalOrderAmount")).getValue();
            double platfromOrderAmountSum = ((Sum) bucket.getAggregations().get("platfromOrderAmount")).getValue();
            double originalReturnAmountSum = ((Sum) bucket.getAggregations().get("originalReturnAmount")).getValue();
            double platfromReturnAmountSum = ((Sum) bucket.getAggregations().get("platfromReturnAmount")).getValue();
            String organizationIdRest = ((TopHits) bucket.getAggregations().get("organizationId")).getHits().getHits()[0].getSourceAsMap().get("organiza" +
                    "tionId").toString();
            String customerNameRest = ((TopHits) bucket.getAggregations().get("customerName")).getHits().getHits()[0].getSourceAsMap().get("customerName").toString();
            String projectManagerNameRest = ((TopHits) bucket.getAggregations().get("projectManagerName")).getHits().getHits()[0].getSourceAsMap().get("projectManagerName").toString();
            String residentNameRest = ((TopHits) bucket.getAggregations().get("residentName")).getHits().getHits()[0].getSourceAsMap().get("residentName").toString();
            String customerServiceNameRest = ((TopHits) bucket.getAggregations().get("customerServiceName")).getHits().getHits()[0].getSourceAsMap().get("customerServiceName").toString();
            return CustomerTradeVolume.builder().inquiryGoodsNumber(inquiryGoodsNumberSum).originalQuotationNumber(originalQuotationNumberSum).
                    platformQuotationNumber(platformQuotationNumberSum).notQuotedGoodsNumber(notQuotedGoodsNumberSum).originalTargetGoodsNumber(originalTargetGoodsNumberSum).
                    platfromTargetGoodsNumber(platfromTargetGoodsNumberSum).originalOrderGoodsNumber(originalOrderGoodsNumberSum).orderNumber(orderNumberSum).
                    originalOrderAmount(originalOrderAmountSum).platfromOrderAmount(platfromOrderAmountSum).originalReturnAmount(originalReturnAmountSum).platfromOrderGoodsNumber(platfromOrderGoodsNumberSum).
                    platfromReturnAmount(platfromReturnAmountSum).organizationId(Long.valueOf(organizationIdRest)).customerName(customerNameRest).
                    projectManagerName(projectManagerNameRest).residentName(residentNameRest).customerServiceName(customerServiceNameRest).build();
        }).collect(Collectors.toList());

        Aggregation countAgg = search.getAggregations().get("count");
        return Result.success(((Cardinality) countAgg).getValue(), "查询成功！", result);
    }

    /**
     * 查询构建
     *
     * @param query
     * @return
     */
    public BoolQueryBuilder getQueryBuilder(CustomerTradeQuery query) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (Objects.nonNull(query.getStart())) {
            boolQueryBuilder.must(QueryBuilders.rangeQuery("time").gte(DateFormatUtils.format(query.getStart(), "yyyy-MM-dd")));
        }
        if (Objects.nonNull(query.getEnd())) {
            boolQueryBuilder.must(QueryBuilders.rangeQuery("time").lt(DateFormatUtils.format(query.getEnd(), "yyyy-MM-dd")));
        }
        if (Objects.nonNull(query.getCustomerName())) {
            boolQueryBuilder.must(QueryBuilders.wildcardQuery("customerName.keyword", "*" + query.getCustomerName() + "*"));
        }
        return boolQueryBuilder;
    }
}
